package com.dayatang.android.Chart;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ExecutionException;

import org.achartengine.model.CategorySeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dayatang.android.Activity.BaseActivity;
import com.dayatang.android.Activity.R;
import com.dayatang.android.Task.BaseTask;

public abstract class AbstractChart extends BaseActivity implements IChart {

	protected final static int StartDATE_DIALOG = 0;
	protected final static int EndDATE_DIALOG = 1;
	
	protected String fromDate;
	protected String toDate;
	
	protected int fromYear,fromMonth;
	protected int toYear,toMonth;
	
	protected Calendar c = null;

	protected LinearLayout layout;

	protected EditText fromEditText,toEditText;
	private Button submitBtn;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.project_outputall_activity);
		
		layout = (LinearLayout) findViewById(R.id.project_outputall_layout);
		
		InitEditText("abc");
		InitBtn();
		InitData();
	}
	
	private void InitBtn(){
		
		submitBtn = (Button) findViewById(R.id.project_outputall_submitBtn);
		submitBtn.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				if(checkEidt()){
					InitData();
				}
			}
		});
		
	}
	
	/**
	 * 子类初始化数据
	 */
	protected abstract void InitData();
	
	/**
	 * 填充报表视图
	 * @param layoutId
	 */
	protected void FillContentView(View view){
		layout.removeAllViews();
		layout.addView(view);
	}
	
	/**
	 * 根据服务端返回的数据执行相应的提示
	 * @param url
	 * @return
	 * @throws ExecutionException 
	 * @throws InterruptedException 
	 */
	protected String CheckServerData(String url) throws InterruptedException, ExecutionException{
		
		String result = new BaseTask(this).execute(url).get();

		if (result.equals("error")) {
			Toast.makeText(this,getString(R.string.server_unknown_error),Toast.LENGTH_LONG).show();
		} else if (result.equals("NoData")) {
			layout.removeAllViews();
			Toast.makeText(this, getString(R.string.project_no_find_data),Toast.LENGTH_LONG).show();
		} else if (result != null) {
			return result;
		}
		
		return null;
	}
	
	protected void InitEditText(String selectArg){
		
		fromEditText = (EditText) findViewById(R.id.reports_from_data_editText);
		toEditText = (EditText) findViewById(R.id.reports_to_data_editText);
		
		if(selectArg.equals("byYear")){
			fromEditText.setOnTouchListener(new TextView.OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					
					Dialog dialog = onCreateDialogByYear(StartDATE_DIALOG);
					dialog.show();
					
					DatePicker datePicker = findDatePicker((ViewGroup)dialog.getWindow().getDecorView());
					if(datePicker != null){
						((ViewGroup) datePicker.getChildAt(0)).getChildAt(1).setVisibility(View.GONE);
						((ViewGroup) datePicker.getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
					}
					
					return false;
				}
			});
			
			toEditText.setOnTouchListener(new TextView.OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					
					Dialog dialog = onCreateDialogByYear(StartDATE_DIALOG);
					dialog.show();
					
					DatePicker datePicker = findDatePicker((ViewGroup)dialog.getWindow().getDecorView());
					if(datePicker != null){
						((ViewGroup) datePicker.getChildAt(0)).getChildAt(1).setVisibility(View.GONE);
						((ViewGroup) datePicker.getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
					}
					
					return false;
				}
			});
		}else if(selectArg.equals("byMonth")){
			
		}else{
			fromEditText.setOnTouchListener(new TextView.OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					showDialog(StartDATE_DIALOG);
					return false;
				}
			});
			
			toEditText.setOnTouchListener(new TextView.OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					showDialog(EndDATE_DIALOG);
					return false;
				}
			});
		}
		
		
		fromDate = fromEditText.getText().toString();
		toDate = toEditText.getText().toString();
		
	}

	private boolean checkEidt(){
		
		fromDate = fromEditText.getText().toString();
		toDate = toEditText.getText().toString();
		
		if(fromDate.equals("") || toDate.equals("")){
			Toast.makeText(this, getString(R.string.reports_alert_noNull), Toast.LENGTH_LONG).show();
			return false;
		}else{
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			
			try {
				Date FromDate = format.parse(fromDate);
				Date ToDate = format.parse(toDate);
				
				if(FromDate.after(ToDate)){
					Toast.makeText(this, getString(R.string.reports_alert_timeBefAft), Toast.LENGTH_LONG).show();
					return false;
				}else{
					return true;
				}
				
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		
		return true;
		
	}
	
	protected Dialog onCreateDialog(int id) {
		
		Dialog dialog = null;
		
		switch(id){
		
			case StartDATE_DIALOG:
				c = Calendar.getInstance();
				dialog = new DatePickerDialog(this, 
						new DatePickerDialog.OnDateSetListener() {
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
									
									fromEditText.setText(year + "-" + (monthOfYear+1) + "-" + dayOfMonth);
							}
						}, 
					c.get(Calendar.YEAR), 
					c.get(Calendar.MONTH), 
					c.get(Calendar.DAY_OF_MONTH)
				);
				break;
			
			case EndDATE_DIALOG:
				c = Calendar.getInstance();
				dialog = new DatePickerDialog(this,
						new DatePickerDialog.OnDateSetListener() {
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
									toEditText.setText(year + "-" + (monthOfYear+1) + "-" + dayOfMonth);
							}
						}, 
					c.get(Calendar.YEAR), 
					c.get(Calendar.MONTH), 
					c.get(Calendar.DAY_OF_MONTH)
				);
				break;
				
		}
		
		return dialog;
	}

	private DatePicker findDatePicker(ViewGroup group) {
        if (group != null) {
            for (int i = 0, j = group.getChildCount(); i < j; i++) {
                View child = group.getChildAt(i);
                if (child instanceof DatePicker) {
                    return (DatePicker) child;
                } else if (child instanceof ViewGroup) {
                    DatePicker result = findDatePicker((ViewGroup) child);
                    if (result != null)
                        return result;
                }
            }
        }
        return null;

    } 

	protected Dialog onCreateDialogByYear(int id) {
		
		Dialog dialog = null;
		
		switch(id){
		
			case StartDATE_DIALOG:
				c = Calendar.getInstance();
				dialog = new DatePickerDialog(this, 
						new DatePickerDialog.OnDateSetListener() {
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
									
									fromEditText.setText(year);
							}
						}, 
					c.get(Calendar.YEAR), 
					c.get(Calendar.MONTH), 
					c.get(Calendar.DAY_OF_MONTH)
				);
				break;
			
			case EndDATE_DIALOG:
				c = Calendar.getInstance();
				dialog = new DatePickerDialog(this,
						new DatePickerDialog.OnDateSetListener() {
							public void onDateSet(DatePicker view, int year, int monthOfYear,
									int dayOfMonth) {
									toEditText.setText(year);
							}
						}, 
					c.get(Calendar.YEAR), 
					c.get(Calendar.MONTH), 
					c.get(Calendar.DAY_OF_MONTH)
				);
				break;
				
		}
		
		return dialog;
	}

	
	//设置chart的属性
	@SuppressWarnings("deprecation")
	protected void setChartSettings(XYMultipleSeriesRenderer renderer,String title, String xTitle, String yTitle, double xMin,double xMax, double yMin, double yMax) {
		
		renderer.setChartTitle(title);
		renderer.setXTitle(xTitle);
		renderer.setYTitle(yTitle);
		renderer.setXAxisMin(xMin);
		renderer.setXAxisMax(xMax);
		renderer.setYAxisMin(yMin);
		renderer.setYAxisMax(yMax);

		renderer.setXLabels(8);
		renderer.setYLabels(11);

		renderer.setXLabelsAlign(Align.CENTER);
		renderer.setYLabelsAlign(Align.CENTER);

		renderer.setShowLegend(false);
		renderer.setShowLabels(true);
		renderer.setShowGrid(false);
		renderer.setZoomButtonsVisible(true);
		renderer.setBarSpacing(1);

		renderer.setDisplayChartValues(false);
		renderer.setChartValuesTextSize(15);

	}



	protected XYMultipleSeriesDataset BuildBarDataset(String[] titles,String[] values) {
		
		XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
		
		CategorySeries  waterSeries = new CategorySeries("Water Temperature");
		
		for (int i = 0, len = values.length; i < len; i++) {
			waterSeries.add(titles[i], Integer.valueOf(values[i]));
		}
	    
	    dataset.addSeries(waterSeries.toXYSeries());
	    
		return dataset;
	}


	protected XYMultipleSeriesRenderer BuildBarRenderer(int colors) {
		
		XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
		renderer.setAxisTitleTextSize(16);
		renderer.setChartTitleTextSize(20);
		renderer.setLabelsTextSize(15);
		renderer.setLegendTextSize(15);
		
		SimpleSeriesRenderer r = new SimpleSeriesRenderer();
		r.setColor(colors);
		renderer.addSeriesRenderer(r);
		
		return renderer;
	}

	public int getArrayMax(String[] num){
		
		int[] max = new int[num.length];
		
		for(int i = 0,len = num.length; i < len; i++){
			max[i] = Integer.valueOf(num[i]);
		}
		
		Arrays.sort(max);
		return max[num.length-1];
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
